/**
 * 
 */
var editionMode=false;
var mapClickedListener;
var routeCoordinates=new Array();
var routePolyline;
var bounds = new google.maps.LatLngBounds();

$(document).ready(function() {
	//Añadir funciones a eventos de los elementos de la pagina
	//Los eventos de Google Maps no se pueden gestionar así
	$("#commentLink").click(function(){
		$("#commentForm:visible").hide("slow");
		$("#commentForm:hidden").show("slow");
		return false;
	});
});
var initFunction = function initialize() {
	var initialLocation = new google.maps.LatLng(24.7756,121.0062);
	//Create the map
	createMap(initialLocation,"auto");
	
	getRoute();
	drawRoute();
	setBoundsToRoute();
	drawPois();
	drawElevation(routeCoordinates);
	if(isCreator){
		paintEditControls();
	}
	setTinyMce();
};

function setTinyMce(){
	google.maps.event.addListener(infoWindow,'domready',function(){
		tinyMCE.execCommand('mceAddControl', false, 'mce_editor_poi'); 
		tinyMCE.execCommand('mceFocus', false, 'mce_editor_poi');
	});
	google.maps.event.addListener(infoWindow,'closeclick',function(){
		tinyMCE.execCommand('mceRemoveControl', false, 'mce_editor_poi');
	});
	google.maps.event.addListener(infoWindow,'position_changed',function(){
		tinyMCE.execCommand('mceRemoveControl', false, 'mce_editor_poi');
	});
}

function getRoute(){
	for (var i = 0; i < route.length; i++) {
		routeCoordinates[i]=new google.maps.LatLng(route[i][0], route[i][1]);
    }
}

function setBoundsToRoute(){
	for(var i =0; i<routeCoordinates.length; i++){
		bounds.extend(routeCoordinates[i]);
	}
	
	map.fitBounds(bounds);
	map.setCenter(bounds.getCenter());
}

function drawRoute(){
	routePolyline = new google.maps.Polyline({
		path: [],
	    strokeColor: "#8181F7",
	    strokeOpacity: 1.0,
	    strokeWeight: 4
	});
	for(var i =0; i<routeCoordinates.length; i++){
		routePolyline.getPath().push(routeCoordinates[i]);
	}
	routePolyline.setMap(map);
	
	var imageInitPos="http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.5|0|04B404|11|_|A";
	initPosMarker = new google.maps.Marker({
	    position: routeCoordinates[0],
	    map: map,
	    icon: imageInitPos
	});
	
	var imageFinalPos="http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.5|0|04B404|11|_|B";
	finalPosMarker = new google.maps.Marker({
	    position: routeCoordinates[i-1],
	    map: map,
	    icon: imageFinalPos
	});
}

function drawPois(){
	for(var i=0;i<pois.length;i++){
		//Leer closures de javascript: http://jibbering.com/faq/notes/closures/
		pois[i].draw();
	}
}

function paintEditControls(){
	//Create resetControl
	var editControlDiv = document.createElement('DIV');
	var markerControl = new MarkerControl(editControlDiv, map);

	editControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_LEFT].push(editControlDiv);
}

function MarkerControl(controlDiv, map) {
	//Define a property to hold the clicked state
	this.clicked_ = false;
	
	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '5px';

	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'groove';
	controlUI.style.borderWidth = '1px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = R_VIEW_CONTROLTITLE;
	controlDiv.appendChild(controlUI);

	// Set CSS for the control interior
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingLeft = '8px';
	controlText.style.paddingRight = '8px';
	controlText.style.paddingTop = '4px';
	controlText.style.paddingBottom = '4px';
	controlText.innerHTML = "<img src=\"http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.3|0|4e84f1|8|_\"/>";
	controlUI.appendChild(controlText);

	// We set up a variable for the 'this' keyword since we're adding event
	// listeners later and 'this' will be out of scope. (Closure)
	var markerControl = this;
	// Setup the click event listeners
	google.maps.event.addDomListener(controlUI, 'click', function(){
		if(markerControl.getClicked()){
			markerControlUnclicked(controlUI);
		}
		else{
			markerControlClicked(controlUI);
		}
		markerControl.setClicked(!markerControl.getClicked());
	});
	
	// Define setters and getters for this property
	this.getClicked = function() {
		return this.clicked_;
	};

	this.setClicked = function(clicked) {
		this.clicked_ = clicked;
	};
}

function markerControlUnclicked(controlUI){
	editionMode=false;
	//Desabilitar arrastre de POIs
	for(var i=0;i<pois.length;i++){
		pois[i].getMarker().setOptions({draggable:false});
	}
	//Sacar el boton
	controlUI.style.borderWidth = '1px';
	//Cambiar el cursor
	var myOptions = {
		draggableCursor: "auto"
	};
	map.setOptions(myOptions);
	google.maps.event.removeListener(mapClickedListener);
}

function markerControlClicked(controlUI){
	editionMode=true;
	//Habilitar arrastre de POIs
	for(var i=0;i<pois.length;i++){
		pois[i].getMarker().setOptions({draggable:true});
	}
	//Hundir el boton
	controlUI.style.borderWidth = '3px';
	//Cambiar el cursor
	var myOptions = {
		draggableCursor: "crosshair"
	};
	map.setOptions(myOptions);
	//Add event listener to the click event
    mapClickedListener=google.maps.event.addListener(map, 'click', function(event){
    	pointOfInterest = new PointOfInterest(event.latLng.lat(),event.latLng.lng(),"NEW");
    	pois[pois.length]=pointOfInterest;
    	pointOfInterest.draw();
    });
}

function POICategory(id){
	this.id_ = id;
	this.name_ = null;
	this.description_ = null;
	this.subCategories_ = null;
	
	this.getId = function() {
		return this.id_;
	};
	this.getName = function(){
		return this.name_;
	};
	this.setName = function(name){
		this.name_=name;
	};
	this.getDescription = function(){
		return this.description_;
	};
	this.setDescription = function(description){
		this.description_=description;
	};
	this.getSubCategories = function(){
		return this.subCategories_;
	};
	this.setSubCategories = function(subCategories){
		this.subCategories_=subCategories;
	};
}

function POISubCategory(id){
	this.id_ = id;
	this.name_ = null;
	this.image_ = null;
	this.description_ = null;
	this.category_ = null;
	
	this.getId = function() {
		return this.id_;
	};
	this.getName = function(){
		return this.name_;
	};
	this.setName = function(name){
		this.name_=name;
	};
	this.getDescription = function(){
		return this.description_;
	};
	this.setDescription = function(description){
		this.description_=description;
	};
	this.getImage = function(){
		return this.image_;
	};
	this.setImage = function(image){
		this.image_=image;
	};
	this.getCategory = function(){
		return this.category_;
	};
	this.setCategory = function(category){
		this.category_=category;
	};
}

function PointOfInterest(lat,lng,status){
	this.status_=status;
	this.lat_=lat;
	this.lng_=lng;
	this.id_ = '';
	this.name_ = "";
	this.descrip_ = "";
	this.image_ = "";
	this.marker_ = null;
	
	// Define setters and getters for properties
	this.getId = function() {
		return this.id_;
	};
	this.setId = function(id) {
		this.id_ = id;
	};
	this.getName = function() {
		return this.name_;
	};
	this.setName = function(name) {
		this.name_ = name;
	};
	this.getDescrip = function() {
		return this.descrip_;
	};
	this.setDescrip = function(descrip) {
		this.descrip_ = descrip;
	};
	this.getImage = function() {
		return this.image_;
	};
	this.setImage = function(image) {
		this.image_ = image;
	};
	this.getMarker = function() {
		return this.marker_;
	};
	this.setMarker = function(marker) {
		this.marker_ = marker;
	};
	this.getLat = function() {
		return this.lat_;
	};
	this.setLat = function(lat) {
		this.lat_ = lat;
	};
	this.getLng = function() {
		return this.lng_;
	};
	this.setLng = function(lng) {
		this.lng_ = lng;
	};
	this.getStatus = function() {
		return this.status_;
	};
	this.setStatus = function(status) {
		this.status_ = status;
	};
	
	this.draw= function(){
		//Esto se hace para que el objeto este presente en la Closure de la función Draw
		//http://blog.morrisjohns.com/javascript_closures_for_dummies.html
		var pointOfInterest=this;
		this.marker_= new google.maps.Marker({
		    map:map,
		    animation: google.maps.Animation.DROP,
		    draggable: editionMode,
		    position: new google.maps.LatLng(this.lat_,this.lng_)
		});
		if(pointOfInterest.getImage()==""){
			pointOfInterest.setImage(poiCategories[0].getSubCategories()[0].getImage());
		}
		var myOptions ={
			icon: 'http://google-maps-icons.googlecode.com/files/'+pointOfInterest.getImage()+'.png'
		};
		this.marker_.setOptions(myOptions);
		
		google.maps.event.addListener(this.marker_, 'click', function(){
			if(pointOfInterest.getStatus()=="OLD"){
				formFunction="return sendEditPOI(this)";
			}
			else if(pointOfInterest.getStatus()=="NEW"){
				formFunction="return sendNewPOI(this)";
			}
			if(editionMode){
				var infoWindowSubCats= '';
				for(var i=0;i<poiCategories.length;i++){
					poiSubCats=poiCategories[i].getSubCategories();
					infoWindowSubCats+='<optgroup label="'+poiCategories[i].getName()+'">';
					for(var j=0;j<poiSubCats.length;j++){
						infoWindowSubCats+='<option value="'+poiSubCats[j].getId()+'">'+poiSubCats[j].getName()+'</option>';
					}
					infoWindowSubCats+='</optgroup>';
				}
				infoWindow.setContent('<div id="content" style="width:300px; height:250px">'+
						'<form action="index.php" method="post" onsubmit="'+formFunction+'">'+
						'<div style="float:left; clear:left">'+
						  	'<div style="float:left; clear:left; width:15%; margin-right:20px;">'+
						  		'<p><b>'+R_VIEW_NAME+':</b></p>'+
						  	'</div>'+
						  	'<div style="float:left; width:30%;">'+
						  		'<input type="text" id="poiName" name="poiName" value="'+pointOfInterest.getName()+'"/>'+
						  	'</div>'+
						  	'<div style="width:15%; float:right;">'+
		  			  			'<input type="submit" id="submit" value="'+R_VIEW_SUBMIT+'"/>'+
		  			  		'</div>'+
		  			  	'</div>'+
		  			  	'<div style="float:left; clear:left; width: 100%; margin-bottom:3px">'+
				  			'<div style="float:left; clear:left; width:15%; margin-right:20px;">'+
						  		'<p><b>'+R_VIEW_CATEGORY+':</b></p>'+
						  	'</div>'+
						  	'<div style="float:left; width:40%;">'+
						  		'<select id="poiSubCategory" name="poiSubCategory" onchange="updatePOIImage(this)">'+
						  			infoWindowSubCats+
						  		'</select>'+
						  	'</div>'+
				  		'</div>'+
					  	'<div style="float:left; clear:left; width: 100%; margin-bottom:3px">'+
					  		'<b>'+R_VIEW_DESCRIPTION+':</b>'+
					  	'</div>'+
					  	'<div id="textMCE" style="clear:left;"><textarea id="mce_editor_poi" id="poiDescrip" name="poiDescrip" style="width:250px">'+pointOfInterest.getDescrip()+'</textarea></div>'+
					  	'<div style="clear:both; float:left;">'+
		  					'<p><a href="#" onClick="return sendDeletePOI('+pointOfInterest.getId()+')">'+R_VIEW_DELETE+'</a></p>'+
		  				'</div>'+
					  	'<input type="hidden" name="poiID" value="'+pointOfInterest.getId()+'" />'+
					  	'</form>'+
				   '</div>');
			}
			else{
				infoWindow.setContent('<div id="content" style="width:250px; height:200px">'+
				    '<div style="float:left; clear:both">'+
						'<p><b>'+pointOfInterest.getName()+'</b></p>'+
				  		'</div>'+
				  	'<div style="float:left; clear:left; width: 100%; margin-bottom:3px">'+
				  		'<p>'+pointOfInterest.getDescrip()+'</p>'+
				  	'</div>'+
				  '</div>');
			}
			infoWindow.open(map,pointOfInterest.getMarker());
			infoWindow.setPosition(pointOfInterest.getMarker().getPosition());
		});
		google.maps.event.addListener(this.marker_, 'dragend', function(){
			if(pointOfInterest.getStatus()=="OLD"){
				position=pointToKML(pointOfInterest.getMarker().getPosition());
				
				editPOIurl="index.php?option=com_socialroutes&task=editRoutePOI&id="+
				  pointOfInterest.getId()+"&routeID="+
				  routeID+"&name="+pointOfInterest.getName()+"&descrip="+
				  pointOfInterest.getDescrip()+"&position="+position+
				  "&view=default&format=raw";
				
				$.ajax({
					type: "GET",
					url: editPOIurl,
					success: function(msg){
						
					}
				});
			}
		});
	};
}

function updatePOIImage(select){
	markerIndex=getSelectedMarkerIndex();
	subCategory=getSubCategoryById(select.value);
	if(subCategory!=null){
		var myOptions ={
			icon: 'http://google-maps-icons.googlecode.com/files/'+subCategory.getImage()+'.png'
		};
		pois[markerIndex].getMarker().setOptions(myOptions);
	}
}

function getSubCategoryById(id){
	var subCategory=null;
	var found=false;
	var i=0;
	while(!found && i<poiCategories.length){
		var j=0;
		poiSubCats=poiCategories[i].getSubCategories();
		while(!found && j<poiSubCats.length){
			if(poiSubCats[j].getId()==id){
				found=true;
				subCategory=poiSubCats[j];
			}
			j++;
		}
		i++;
	}
	return subCategory;
}

function getSelectedMarkerIndex(){
	var found=false;
	var i=0;
	while(!found && i<pois.length){
		if(pois[i].getMarker().getPosition().lat()==infoWindow.getPosition().lat() &&
		   pois[i].getMarker().getPosition().lng()==infoWindow.getPosition().lng()){
			found=true;
		}
		else{
			i++;
		}
	}
	if(!found)
		return -1;
	return i;
}

function getPOIById(id){
	var found=false;
	var i=0;
	while(!found && i<pois.length){
		if(pois[i].getId()==id){
			found=true;
		}
		else{
			i++;
		}
	}
	if(!found)
		return -1;
	return i;
}

function sendNewPOI(form){
	name=form.poiName.value;
	subCategory=form.poiSubCategory.value;
	descrip=tinyMCE.activeEditor.getContent();
	if(name=="" || descrip==""){
		alert(R_VIEW_ALERTNAMEDESCRIP);
		return false;
	}
	position=pointToKML(infoWindow.getPosition());

	addPOIurl="index.php?option=com_socialroutes&task=addRoutePOI&routeID="+
	  routeID+"&name="+name+"&descrip="+
	  descrip+"&position="+position+"&subCategory="+subCategory+
	  "&view=default&format=raw";
	infoWindow.close();
	$.ajax({
		type: "GET",
		url: addPOIurl,
		success: function(msg){
			//Setear la ID en el POI en cuestion de javascript y que pase a ser OLD
			i=getSelectedMarkerIndex();
			if(i>=0){
				pois[i].setName(name);
				pois[i].setDescrip(descrip);
				pois[i].setId(msg);
				pois[i].setStatus("OLD");
			}
		}
	});
	return false;
}

function sendEditPOI(form){
	id=form.poiID.value;
	name=form.poiName.value;
	subCategory=form.poiSubCategory.value;
	descrip=tinyMCE.activeEditor.getContent();
	if(name=="" || descrip==""){
		alert(R_VIEW_ALERTNAMEDESCRIP);
		return false;
	}
	position=pointToKML(infoWindow.getPosition());
	
	editPOIurl="index.php?option=com_socialroutes&task=editRoutePOI&id="+
	  id+"&routeID="+
	  routeID+"&name="+name+"&descrip="+
	  descrip+"&position="+position+"&subCategory="+subCategory+
	  "&view=default&format=raw";
	
	infoWindow.close();
	
	$.ajax({
		type: "GET",
		url: editPOIurl,
		success: function(msg){
			//Setear los nuevos valores en el POI en cuestion de javascript
			i=getSelectedMarkerIndex();
			if(i>=0){
				pois[i].setName(name);
				pois[i].setDescrip(descrip);
			}
		}
	});
	return false;
}

function sendDeletePOI(id){
	i=getSelectedMarkerIndex();
	if(pois[i].getStatus()=="OLD"){
		deletePOIurl="index.php?option=com_socialroutes&task=deleteRoutePOI&id="+
		  id+"&routeID="+
		  routeID+
		  "&view=default&format=raw";
	
		//Eliminar el POI del array y del mapa
		infoWindow.close();
		i=getSelectedMarkerIndex();
		if(i>=0){
			pois[i].getMarker().setMap(null);
			pois[i].setStatus("DELETED");
		}
		
		$.ajax({
			type: "GET",
			url: deletePOIurl,
			success: function(msg){
				//Lo hacemos antes para que no de sensacion de lentitud
				//TODO: Habria que fijarse si ha tenido exito. Si no, volver a pintar el POI.
			}
		});
	}
	else if(pois[i].getStatus()=="NEW"){
		infoWindow.close();
		pois[i].setStatus("DELETED");
		pois[i].getMarker().setMap(null);
	}
	
	return false;
}